package com.jalarbee.web.jsf.controller;

import com.jalarbee.stock.product.business.Product;
import com.jalarbee.stock.product.business.SimpleProduct;
import com.jalarbee.stock.product.service.ProductService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ProductController {

    private ProductService productService;
    private CategoriesController categories;
    private Product product;
    private static final Logger logger = LoggerFactory.getLogger(ProductController.class);

    public void setProductService(ProductService productService) {
        this.productService = productService;
    }

    public void setCategories(CategoriesController categories) {
        this.categories = categories;
    }

    public void setProduct(Product product) {
        logger.info("setting product...");
        this.product = product;
    }

    public CategoriesController getCategories() {
        return categories;
    }

    public ProductController() {
        logger.info("new ProductConroller instantiation...");
    }

    public void newProduct() {
        initProduct();
    }

    public String add() {
        try {
            productService.create(product);
            return Navigation.SUCCESS;
        } catch (Exception e) {
            return Navigation.ERROR;
        }
    }

    public void update() {
        productService.update(product);
    }

    public void reload() {
        productService.read(product.getId());
    }

    public void inactivate() {
        productService.inactivate(product);
    }

    public void activate() {
        productService.activate(product);
    }

    public Product getProduct() {
        if (product == null) {
            initProduct();
        }
        return product;
    }

    public void setProductCopy() {
        resetProductId();
    }

    private void initProduct() {
        product = new SimpleProduct();
    }

    private Product makeCopyOfCurrentProduct() {
        Product p = new SimpleProduct();
        p.setAvailability(product.getAvailability());
        p.setCreditPrice(product.getCreditPrice());
        p.setDefaultCategory(product.getDefaultCategory());
        p.setDescription(product.getDescription());
        p.setName(product.getName());
        p.setSmallestTradabeUnit(product.getSmallestTradabeUnit());
        p.setStatus(product.getStatus());
        p.setStockPrice(product.getStockPrice());
        p.setRetailPrice(product.getRetailPrice());
        return p;
    }

    private void resetProductId() {
        product.setId(0);
    }
}
